package com.example.alioss.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 聊天
 */
@Controller
@RequestMapping("/chat")
public class ChatController {

    @RequestMapping("/html")
    public String picUpload(Map<String, Object> map) {//跳转到 upload.html
        map.put("hello", "EventSource连接");
        return "chatPage";
    }

    @ResponseBody
    @CrossOrigin
    @RequestMapping(value = "/getConnection", produces = "text/event-stream;charset=UTF-8")
    public void getDate(String nickName, HttpServletResponse response) throws Exception {
        System.out.println("getDate event start" + nickName);
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(200);
        while (!response.getWriter().checkError()) {
            String currentTime = new SimpleDateFormat("yyyyMMdd hh:mm:ss").format(new Date());
            response.getWriter().write("data:" + nickName + ">>" + currentTime + "\n\n");
            response.getWriter().flush();
            Thread.sleep(1000);
        }
        response.getWriter().close();
        System.out.println("getDate event end");
    }

}
